/**
 * 
 */
package com.study.reflect;

import java.io.File;
import java.lang.reflect.Field;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.study.reflect.entity.UserEntity;

/**
 * @author Administrator
 * @date 2019年4月24日
 */
public class ReflectTest {

	public static void main(String[] args) throws Exception {

		//ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext(
		//		"D:\\06java\\workspace\\study-demo\\src\\main\\java\\com\\study\\reflect\\application.xml");
		ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext(
				"application1.xml");
		
		UserEntity bean = (UserEntity) classPathXmlApplicationContext.getBean("user1");

		System.out.println(bean);
	}

}

/**
 * @author Administrator
 * @date 2019年4月24日
 */
class ClassPathXmlApplicationContext {

	private String xmlPath;
	
	/**
	 * @param string
	 */
	public ClassPathXmlApplicationContext(String string) {
		this.xmlPath = string;
	}
	
	public Object getBean(String beanId) throws Exception {
		
		SAXReader saxReader = new SAXReader();
		//Document read = saxReader.read(new File(getXmlPath()));
		Document read = (Document) saxReader.read(this.getClass().getClassLoader().getResourceAsStream(getXmlPath()));
		Element rootElement = read.getRootElement();
		
		List<Element> elements = rootElement.elements("bean");
		for(Element element : elements){
			Attribute attrId = element.attribute("id");
			if(attrId.getValue().equals(beanId)){
				Attribute attrClass = element.attribute("class");
				Class<?> cls = Class.forName(attrClass.getValue());
				
				Object newInstance = cls.newInstance();
				
				List<Element> propertiesElements = element.elements("property");
				for(Element pe : propertiesElements){
					Attribute attrName = pe.attribute("name");
					String name = attrName.getValue();
//					Attribute attrValue = pe.attribute("value");
//					String value = attrValue.getValue();
					String value = pe.attributeValue("value");
					Field declaredField = cls.getDeclaredField(name);
					
					declaredField.setAccessible(true);
					declaredField.set(newInstance, value);
					
				}
				return newInstance;
			}
		}
		
		return null;
		
	}

	
	
	/**
	 * @return the xmlPath
	 */
	public String getXmlPath() {
		return xmlPath;
	}

	/**
	 * @param xmlPath the xmlPath to set
	 */
	public void setXmlPath(String xmlPath) {
		this.xmlPath = xmlPath;
	}

}